from django.shortcuts import render

from index.models import *


def ranking_default(requset):
    return ranking_view(requset, 0, 1)


def ranking_view(requset, type, page):
    # 先显示类型
    label_all = Label.objects.all()

    if type:
        songs = Dynamic.objects.filter(song__label_id=type).order_by('-plays')
    else:
        songs = Dynamic.objects.all().order_by('-plays')

    # 根据类型获取数据
    # 数据分页
    from django.core.paginator import Paginator
    paginator = Paginator(songs, 5)
    # object_list: 一个可迭代对象
    # per_page : 每一页的数量，默认是25

    if not isinstance(page, int):  # 判断是否是数字
        songs = paginator.page(1)
    elif paginator.num_pages < page:  # 判断是否超出服务
        songs = paginator.page(paginator.num_pages)
    elif 1 > page:  # 判断页码是否小于1
        songs = paginator.page(1)
    else:
        songs = paginator.page(page)

    # 生成一个范围 判断范围内哪些可以正常使用-1 0 1 2 3
    page_list = []
    page_range = 1  # 当前页码的前后显示数量
    for i in range(page - page_range, page + page_range + 1):
        if 0 < i <= paginator.num_pages:
            page_list.append(i)

    return render(requset, 'ranking.html', {'label_all': label_all,
                                            'page': (page - 1) * 5,
                                            'page_list': page_list,
                                            'paginator': paginator,
                                            'dynamic': songs,
                                            'type': type})
